using Microsoft.Extensions.Logging;
using MessagePack;

namespace SeataNet.Core.Serialization
{
    /// <summary>
    /// MessagePack序列化器 (.NET替代Kryo的高性能序列化器)
    /// </summary>
    public class MessagePackSerializer : ISerializer
    {
        private readonly ILogger<MessagePackSerializer> _logger;
        private readonly MessagePackSerializerOptions _options;

        public MessagePackSerializer(ILogger<MessagePackSerializer> logger)
        {
            _logger = logger;
            _options = MessagePackSerializerOptions.Standard
                .WithCompression(MessagePackCompression.Lz4BlockArray);
        }

        public SerializerType Type => SerializerType.MessagePack;

        public byte[] Serialize<T>(T obj)
        {
            try
            {
                if (obj == null)
                {
                    return Array.Empty<byte>();
                }

                return global::MessagePack.MessagePackSerializer.Serialize(obj, _options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MessagePack序列化失败");
                throw;
            }
        }

        public T Deserialize<T>(byte[] data)
        {
            try
            {
                if (data == null || data.Length == 0)
                {
                    return default;
                }

                return global::MessagePack.MessagePackSerializer.Deserialize<T>(data, _options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MessagePack反序列化失败");
                throw;
            }
        }

        public byte[] Serialize(object obj, Type type)
        {
            try
            {
                if (obj == null)
                {
                    return Array.Empty<byte>();
                }

                return global::MessagePack.MessagePackSerializer.Serialize(type, obj, _options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"MessagePack序列化失败: {type.Name}");
                throw;
            }
        }

        public object Deserialize(byte[] data, Type type)
        {
            try
            {
                if (data == null || data.Length == 0)
                {
                    return null;
                }

                return global::MessagePack.MessagePackSerializer.Deserialize(type, data, _options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"MessagePack反序列化失败: {type.Name}");
                throw;
            }
        }
    }
}
